﻿using AutoMapper;
using MediatR;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Slaughter;
using Provenance.Write.Api.Application.Command.Slaughter;

namespace Provenance.Write.Api.Application.CommandHandler.Slaughter
{
    public class UpSlaughterInfoCommandHandler : IRequestHandler<UpSlaughterInfoCommand, ApiResult>
    {
        private readonly ISlaughterInfoRepository _slaughterInfoRepository;
        private readonly ILogger<UpSlaughterInfoCommandHandler> _logger;
        private readonly IMapper _mapper;
        public UpSlaughterInfoCommandHandler(ISlaughterInfoRepository slaughterInfoRepository, ILogger<UpSlaughterInfoCommandHandler> logger, IMapper mapper)
        {
            _slaughterInfoRepository = slaughterInfoRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult> Handle(UpSlaughterInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _slaughterInfoRepository.GetAsync(x => x.SlaughterInfoId == request.SlaughterInfoId);
                obj = _mapper.Map(request, obj);
                await _slaughterInfoRepository.UpdateEntity(obj);
                return ApiResult.Success();
            }
            catch (Exception ex)
            {
                _logger.LogError("Error updating slaughter info: " + ex.Message);
                return ApiResult.Failure(ex.Message);
            }
        }
    }
}
